package com.supcalls;

import javax.script.*;

public class NashornExample {
    public static void main(String[] args) {
        try {
            // 创建脚本引擎
            ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");

            // 运行简单的 JavaScript 代码
            engine.eval("print('Hello from Nashorn!');");

            // 执行带参数的 JavaScript 代码
            String script = "function greet(name) { return 'Hello, ' + name; }";
            engine.eval(script);
            Invocable invocable = (Invocable) engine;
            String result = (String) invocable.invokeFunction("greet", "Java");
            System.out.println(result);  // 输出：Hello, Java

            // 可以传递 Java 对象给 JavaScript
            engine.put("myVar", 42);
            engine.eval("print('The value of myVar is: ' + myVar);");

        } catch (ScriptException | NoSuchMethodException e) {
            e.printStackTrace();
        }
    }
}

